package com.suyx.job.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;

import com.suyx.job.entity.EmailContent;
import com.suyx.job.entity.EmailServerInfo;

import javax.mail.Message;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/26 0026 16:25
 * @Description:
 */
@Slf4j
public class EmailUtils {

    /**
     * 发送邮箱
     */
    public void sendEmail(EmailServerInfo emailServerInfo, EmailContent content) throws Exception {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        //设置邮件服务器
        javaMailSender.setHost(emailServerInfo.getHost());
        javaMailSender.setUsername(emailServerInfo.getUserName());
        javaMailSender.setPassword(emailServerInfo.getPassword());
        javaMailSender.setPort(emailServerInfo.getPort());

        //建立邮件消息
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper msgHelper = new MimeMessageHelper(msg, true, "utf-8");
        //发送者
        msgHelper.setFrom(emailServerInfo.getSendAddress());
        //接收方
        msg.setRecipients(Message.RecipientType.TO, emailServerInfo.getReceivingAddress());
        //抄送地址
        String ccAddress = emailServerInfo.getCcAddress();
        if (!StringUtils.isEmpty(ccAddress)) {
            msg.setRecipients(Message.RecipientType.CC, convert(ccAddress));
        }
        //发送的标题
        msgHelper.setSubject(content.getSubject());
        //发送的内容
        msgHelper.setText(content.getText());

        javaMailSender.send(msg);
    }

    private InternetAddress[] convert(String address) throws AddressException {
        InternetAddress[] internetAddress;
        if (address.indexOf(',') == -1) {
            internetAddress = new InternetAddress[]{new InternetAddress(address)};
        } else {
            String[] c = address.split(",");
            internetAddress = new InternetAddress[c.length];
            for (int i = 0; i < c.length; i++) {
                internetAddress[i] = new InternetAddress(c[i]);
            }
        }
        return internetAddress;
    }

}
